// 起始时间戳（比如 2021-01-01）
const EPOCH = 1609459200000n;

let machineId = 1n; // 可自定义客户端编号
let sequence = 0n;
let lastTimestamp = -1n;

function currentTimestamp(): bigint {
  return BigInt(Date.now());
}

export function generateSnowflakeId(): string {
  let timestamp = currentTimestamp();

  if (timestamp === lastTimestamp) {
    sequence = (sequence + 1n) & 0xfffn; // 4095，12位序列号
    if (sequence === 0n) {
      while ((timestamp = currentTimestamp()) <= lastTimestamp) {
        // 等待下一毫秒
      }
    }
  } else {
    sequence = 0n;
  }

  lastTimestamp = timestamp;

  const id = ((timestamp - EPOCH) << 22n) | (machineId << 12n) | sequence;
  return id.toString();
}
